import { asyncRoutes, constantRoutes } from '@/router'

import lodash from 'lodash'

/*
 * 通过递归过滤异步路由表
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes &&
    routes.forEach(route => {
      roles &&
        roles.forEach(item => {
          if (item.path == route.name) {
            if (item.children && item.children.length > 0) {
              route.children = filterAsyncRoutes(route.children, item.children)
            }
            res.push(route)
          }
        })
    })

  // return routes // 不走权限验证，默认显示所有路由（仅本地测试使用）
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let cloneRoute = lodash.cloneDeep(asyncRoutes)
      let accessedRoutes = filterAsyncRoutes(cloneRoute, roles)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
